import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Button,
  Card,
  Space,
  Spin,
  Form,
  Input,
  InputNumber,
  Select,
  TimePicker,
  TreeSelect,
  Modal,
  message
} from 'antd';
import { ArrowLeftOutlined, InfoCircleOutlined } from '@ant-design/icons';
import CompanySelect from '../../components/select/CompanySelect';
import { useStore, observer } from '../../store/task/storeHook';
import {
  appTypes,
  booleanOptions,
  taskFrequencies
} from '../../data/statusData';
import { trimObject } from '../../utils/dataUtils';

const { TextArea } = Input;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 }
};

const days: any[] = [{
  value: 0,
  text: '星期日',
}, {
  value: 1,
  text: '星期一',
}, {
  value: 2,
  text: '星期二',
}, {
  value: 3,
  text: '星期三',
}, {
  value: 4,
  text: '星期四',
}, {
  value: 5,
  text: '星期五',
}, {
  value: 6,
  text: '星期六',
}];

const times: any[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(value => (
  value === 0 ? {
    value: value,
    text: '不重试'
  } : {
    value: value,
    text: '重试' + value + '次'
  }
));

const CreateTask: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();
  const store: any = useStore();

  const [targetAppType, setTargetAppType] = useState<string>('');
  const [taskFrequency, setTaskFrequency] = useState<string>('');
  const [maxRetryCount, setMaxRetryCount] = useState<number>(0);

  const resetDepartments = (target: boolean) => {
    if (target) {
      form.setFieldsValue({ targetDepartmentId: undefined });
      store.task.fetchDepartments(true, form.getFieldValue('targetCompany'), form.getFieldValue('targetAppType'));
    } else {
      form.setFieldsValue({ sourceDepartmentId: undefined });
      store.task.fetchDepartments(false, form.getFieldValue('sourceCompany'), form.getFieldValue('sourceAppType'));
    }
  };

  const saveRecord = (values: any) => {
    form.setFieldsValue(trimObject(values));
    const data: any = { ...values };
    data.sourceCompanyId = data.sourceCompany[0].value;
    data.targetCompanyId = data.targetCompany[0].value;
    delete data.sourceCompany;
    delete data.targetCompany;
    data.sourceDepartmentName = store.task.getDepartmentNameById(false, data.sourceDepartmentId);
    data.targetDepartmentName = store.task.getDepartmentNameById(true, data.targetDepartmentId);
    data.active = true;
    data.hour = data.time.hour();
    data.minute = data.time.minute();
    delete data.time;
    if (data.targetCompanyId === data.sourceCompanyId && data.targetAppType === data.sourceAppType) {
      messageApi.warning('来源公司及应用类型和目标公司及应用类型不能相同');
      return;
    }
    store.task.saveData(data).then((res: any) => {
      store.task.setSaving(false);
      if (res.success) {
        modal.success({
          title: '任务创建成功',
          onOk() {
            navigate('/task_list');
          }
        });
      } else {
        messageApi.error(res.message);
      }
    });
  };

  return (
    <Spin
      size="large"
      spinning={false}
    >
      {contextHolder}
      {modalContextHolder}
      <Space
        direction="vertical"
        size={[0, 16]}
        style={{ width: '100%', padding: 16 }}
      >
        <Card
          title="创建任务"
          extra={
            <Button
              size="small"
              type="link"
              style={{ padding: 0}}
              onClick={() => navigate(-1)}
            >
              <ArrowLeftOutlined />
              返回
            </Button>
          }
        >
          <Form
            {...layout}
            form={form}
            name="form"
            autoComplete="off"
            style={{ maxWidth: 800, paddingTop: 16 }}
            onFinish={saveRecord}
            onFinishFailed={() => messageApi.warning('数据校验错误')}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '任务标题不能为空'}]}
            >
              <Input maxLength={128} />
            </Form.Item>
            <Form.Item
              name="sourceCompany"
              label="来源公司"
              rules={[{ required: true, message: '来源公司不能为空'}]}
            >
              <CompanySelect
                selectId="form_sourceCompany"
                style={{ maxWidth: 480 }}
                onChange={() => resetDepartments(false)}
              />
            </Form.Item>
            <Form.Item
              name="sourceAppType"
              label="来源应用类型"
              rules={[{ required: true, message: '来源应用类型不能为空'}]}
            >
              <Select
                options={appTypes}
                style={{ width: 120 }}
                onChange={() => resetDepartments(false)}
              />
            </Form.Item>
            <Form.Item
              name="sourceDepartmentId"
              label="来源部门"
              rules={[{ required: true, message: '来源部门不能为空'}]}
            >
              <TreeSelect
                placeholder="选择部门"
                allowClear
                fieldNames={{
                  label: 'title',
                  value: 'key',
                  children: 'children'
                }}
                treeData={store.task.sourceDepartemnts}
                treeExpandedKeys={store.task.sourceExpandedKeys}
                style={{ maxWidth: 480 }}
                onTreeExpand={(keys: any[]) => store.task.setExpandedKeys(false, keys)}
              />
            </Form.Item>
            <Form.Item
              name="targetCompany"
              label="目标公司"
              rules={[{ required: true, message: '目标公司不能为空'}]}
            >
              <CompanySelect
                selectId="form_targetCompany"
                style={{ maxWidth: 480 }}
                onChange={() => resetDepartments(true)}
              />
            </Form.Item>
            <Form.Item
              name="targetAppType"
              label="目标应用类型"
              rules={[{ required: true, message: '目标应用类型不能为空'}]}
            >
              <Select
                options={appTypes}
                style={{ width: 120 }}
                onChange={(value: string) => {
                  setTargetAppType(value);
                  form.setFieldValue('defaultPassword', undefined);
                  resetDepartments(true);
                }}
              />
            </Form.Item>
            <Form.Item
              name="targetDepartmentId"
              label="目标部门"
              rules={[{ required: true, message: '目标部门不能为空'}]}
            >
              <TreeSelect
                placeholder="选择部门"
                allowClear
                fieldNames={{
                  label: 'title',
                  value: 'key',
                  children: 'children'
                }}
                treeData={store.task.targetDepartemnts}
                treeExpandedKeys={store.task.targetExpandedKeys}
                style={{ maxWidth: 480 }}
                onTreeExpand={(keys: any[]) => store.task.setExpandedKeys(true, keys)}
              />
            </Form.Item>
            {
              targetAppType === 'Netease' ? (
                <Form.Item
                  name="defaultPassword"
                  label="默认密码(网易邮箱)"
                  rules={[
                    { min: 6, message: '默认密码不能少于6位' },
                    { max: 16, message: '默认密码不能超过16位' }
                  ]}
                  tooltip={{ title: '网易邮箱创建账号时的默认密码', icon: <InfoCircleOutlined /> }}
                >
                  <Input
                    maxLength={16}
                    style={{ width: 200 }}
                  />
                </Form.Item>
              ) : null
            }
            <Form.Item
              name="includingChildren"
              label="包含子部门"
              rules={[{ required: true, message: '包含子部门不能为空'}]}
            >
              <Select
                options={booleanOptions}
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="includingEmployees"
              label="包含雇员"
              rules={[{ required: true, message: '包含雇员不能为空'}]}
            >
              <Select
                options={booleanOptions}
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="deleteNonExistentChildren"
              label="删除不存在的子部门"
              rules={[{ required: true, message: '删除不存在的子部门不能为空'}]}
            >
              <Select
                options={booleanOptions}
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="frequency"
              label="同步频率"
              rules={[{ required: true, message: '同步频率不能为空'}]}
            >
              <Select
                options={taskFrequencies}
                style={{ width: 80 }}
                onChange={(value: string) => {
                  setTaskFrequency(value);
                  form.setFieldValue('dayOfWeek', undefined);
                  form.setFieldValue('dayOfMonth', undefined);
                }}
              />
            </Form.Item>
            {
              taskFrequency === 'Weekly' ? (
                <Form.Item
                  name="dayOfWeek"
                  label="执行日"
                  rules={[{ required: true, message: '执行日不能为空' }]}
                >
                  <Select style={{ width: 120 }}>
                    {
                      days.map(item => (
                        <Select.Option key={item.value} value={item.value}>
                          {item.text}
                        </Select.Option>
                      ))
                    }
                  </Select>
                </Form.Item>
              ) : null
            }
            {
              taskFrequency === 'Monthly' ? (
                <Form.Item
                  name="dayOfMonth"
                  label="执行日"
                  rules={[{ required: true, message: '执行日不能为空' }]}
                  tooltip={{ title: '正数代表每月第几天，负数代表每月倒数第几天，0和1一样代表每月第1天', icon: <InfoCircleOutlined /> }}
                >
                  <InputNumber
                    max={31}
                    min={-31}
                    precision={0}
                    style={{ width: 80 }}
                  />
                </Form.Item>
              ) : null
            }
            <Form.Item
              name="time"
              label="执行时间"
              rules={[{ required: true, message: '执行时间不能为空'}]}
            >
              <TimePicker
                format="HH:mm"
                placeholder=""
                style={{ width: 80 }}
              />
            </Form.Item>
            <Form.Item
              name="maxRetryCount"
              label="最大重试次数"
              rules={[{ required: true, message: '最大重试次数不能为空' }]}
            >
              <Select
                style={{ width: 120 }}
                onChange={(value: number) => {
                  setMaxRetryCount(value);
                  if (value === 0) {
                    form.setFieldValue('retryInterval', 0);
                  }
                }}
              >
                {
                  times.map(item => (
                    <Select.Option key={item.value} value={item.value}>
                      {item.text}
                    </Select.Option>
                  ))
                }
              </Select>
            </Form.Item>
            {
              maxRetryCount > 0 ? (
                <Form.Item
                  name="retryInterval"
                  label="重试间隔"
                  rules={[{ required: true, message: '重试间隔不能为空' }]}
                  tooltip={{ title: '重试间隔单位为分钟', icon: <InfoCircleOutlined /> }}
                >
                  <InputNumber
                    max={60}
                    min={1}
                    precision={0}
                    style={{ width: 80 }}
                  />
                </Form.Item>
              ) : null
            }
            <Form.Item
              name="remark"
              label="备注"
            >
              <TextArea
                maxLength={256}
                rows={3}
              />
            </Form.Item>
            <Form.Item
              {...tailLayout}
            >
              <Space style={{ marginTop: 16 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  提交
                </Button>
                <Button
                  htmlType="button"
                  onClick={() => {
                    form.resetFields();
                    resetDepartments(false);
                    resetDepartments(true);
                    setTaskFrequency('');
                    setMaxRetryCount(0);
                  }}
                >
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </Space>
    </Spin>
  );
};

export default observer(CreateTask);
